﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Common.Logging;
using Happy.ExceptionHanding;
using Happy.Web.Mvc.Newtonsoft;

namespace Happy.Web.Mvc.ExceptionHanding
{
    /// <summary>
    /// 处理应用程序未捕获的异常。
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class WriteExceptionResultAttribute : FilterAttribute, IExceptionFilter
    {
        /// <inheritdoc />
        public void OnException(ExceptionContext filterContext)
        {
            var exception = filterContext.Exception;
            if (!FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
            {
                LogManager.GetCurrentClassLogger().Error(exception);
            }
            filterContext.Result = CreateErrorResult(exception);
            filterContext.ExceptionHandled = true;
        }

        private static ActionResult CreateErrorResult(Exception exception)
        {
            var information = ExceptionInformationProviderRegistry.CreateInformation(exception);

            return new NewtonsoftJsonResult
            {
                Data = information
            };
        }
    }
}